package com.xb.loan.util;

import com.xb.loan.util.file.FileLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

public class PropertiesManager {

	private static Map<String,String> map = new HashMap<String,String>();
	private static Set<String> pathSet = new HashSet<String>();
	private static int FILEPATH_TYPE = FileLoader.TYPE_CLASSPATH;
	private static Log logger = LogFactory.getLog(PropertiesManager.class);

	public static Map<String,String> getTemplateMap() {
		
		return map;
	}

	public static String getValue(String key) {
		
		return map.get(key);
	}
	
	public static void addConfig(String path, int pathType) {

		if(!isContainPath(path)){
			
			pathSet.add(path);
			loadConfig(path, pathType);
		}
	}
	
	public static synchronized void loadConfigByClassPath(String path) {
		
		if(!isContainPath(path)){
			
			pathSet.add(path);
			loadConfig(path, FILEPATH_TYPE);
		}
	}
	
	private static synchronized void loadConfig(String path, int pathType) {
		
        logger.info("Properties manager init,filepath=" + path );
        Properties pro = FileLoader.loadPro(path, pathType);
        if(pro != null && pro.size() > 0 ){
        	Set<Object> set = pro.keySet();
        	Iterator it = set.iterator();
        	while(it.hasNext()){
        		String key = (String)it.next();
        		map.put(key, pro.getProperty(key));
        		logger.info("Properties manager add key value is " + key + " " + pro.getProperty(key));
        	}
        }
	}
	
	private static boolean isContainPath(String path){
		
		if(path != null && !"".equals(path)){
			if(pathSet.contains(path)){
			
				return true;
			}else{
				
				return false;
			}
		}
		return false;
	}
	
}
